package com.usian.wemedia.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.common.fastdfs.FastDFSClientUtil;
import com.usian.common.medis.NewsAutoScanConstants;
import com.usian.common.medis.WedisContans;
import com.usian.model.admin.dtos.NewsAuthDto;
import com.usian.model.common.dtos.PageResponseResult;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.media.dtos.*;
import com.usian.model.media.pojos.*;
import com.usian.utils.threadlocal.WmThreadLocalUtils;
import com.usian.wemedia.wemedia.mapper.MertilMapper;
import com.usian.wemedia.wemedia.mapper.NewsMaterialMapper;
import com.usian.wemedia.wemedia.mapper.WmNewsMapper;
import com.usian.wemedia.wemedia.service.MediaServiceUpload;
import org.apache.kafka.clients.admin.KafkaAdminClient;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class MaterialServiceImpl extends ServiceImpl<MertilMapper, WmMaterial> implements MediaServiceUpload {

    @Value(value = "${fileServerUrl}")
    private String filename;

    @Autowired
    private FastDFSClientUtil fastDFSClientUtil;

    @Resource
    private NewsMaterialMapper newsMaterialMapper;

    @Resource
    private WmNewsMapper wmNewsMapper;

    @Resource
    private  MertilMapper mertilMapper;

    @Autowired
    private KafkaTemplate kafkaTemplate;

    @Override
    public ResponseResult upload(MultipartFile multipartFile) {
        //判断是否是空
        if(multipartFile==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        String ss=null;
        //上传文件
        try {
            ss = fastDFSClientUtil.uploadFile(multipartFile);
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR,"文件上传失败");
        }
        //添加到数据库
        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setCreatedTime(new Date());
        wmMaterial.setIsCollection(0);
        wmMaterial.setType(0);
        //从共享本地线程中获取值
        WmUser user = WmThreadLocalUtils.getUser();
        wmMaterial.setUserId(user.getApUserId());
        wmMaterial.setUrl(filename+ss);
        //添加
        save(wmMaterial);
        //封装返回
        return ResponseResult.okResult(0,wmMaterial.getUrl());
    }

    @Override
    public ResponseResult findpage(WmMaterialDto wmMaterialDto) {
        //判断参数
        if(wmMaterialDto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        wmMaterialDto.checkParam();

        //进行查询
        LambdaQueryWrapper<WmMaterial> queryWrapper = new LambdaQueryWrapper<>();
        WmUser user = WmThreadLocalUtils.getUser();
        queryWrapper.eq(WmMaterial::getUserId,user.getApUserId());
        queryWrapper.eq(wmMaterialDto.getIsCollection()!=null,WmMaterial::getIsCollection,wmMaterialDto.getIsCollection());
        Page page3 = new Page(wmMaterialDto.getPage(), wmMaterialDto.getSize());
        Page page = page(page3, queryWrapper);

        //封装参数
        ResponseResult responseResult = new PageResponseResult(wmMaterialDto.getPage(), wmMaterialDto.getSize(), (int) page.getTotal());
        responseResult.setData(page.getRecords());
        return responseResult;
    }

    @Override
    public ResponseResult del(Integer id) {
        //判断参数是否为空
        if(id==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //进行查询
        LambdaQueryWrapper<WmNewsMaterial> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WmNewsMaterial::getMaterialId,id);
        Integer integer = newsMaterialMapper.selectCount(queryWrapper);
        //判断是否有关联频道
        if(integer>0){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"有频道关联，不可删除");
        }
        //查询进行删除
        WmMaterial byId = getById(id);
        String replace = byId.getUrl().replace(filename, "");
        fastDFSClientUtil.delFile(replace);
        removeById(id);
        return ResponseResult.errorResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult collect(Integer id, int i) {
        if (id==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        LambdaUpdateWrapper<WmMaterial> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(WmMaterial::getIsCollection,i);
        updateWrapper.eq(WmMaterial::getId,id);
        update(updateWrapper);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult newsfindPage(WmNewsPageReqDto dto) {
        //判断是否为空
        if(dto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //检查分页参数
        dto.checkParam();

        //判断是否登录
        WmUser user = WmThreadLocalUtils.getUser();
        if(user==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"您还没有登录或者token过期请重新登录!!!");
        }

        //开始进行分页
        LambdaQueryWrapper<WmNews> queryWrapper = new LambdaQueryWrapper<>();

        //状态
        queryWrapper.eq(dto.getStatus()!=null,WmNews::getStatus,dto.getStatus());

        //频道
        queryWrapper.eq(dto.getChannelId()!=null,WmNews::getChannelId,dto.getChannelId());

        //关键字
        queryWrapper.like(dto.getKeyword()!=null,WmNews::getTitle,dto.getKeyword());

        //时间
        queryWrapper.between(dto.getBeginPubDate()!=null&&dto.getEndPubDate()!=null
                ,WmNews::getPublishTime,dto.getBeginPubDate(),dto.getEndPubDate());


        //开始分页
        Page page = new Page(dto.getPage(), dto.getSize());
        Page page1 = wmNewsMapper.selectPage(page, queryWrapper);

        //封装数据进行返回
        ResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(),(int)page1.getTotal());
        responseResult.setData(page1.getRecords());
        return responseResult;
    }

    @Override
    public ResponseResult submitnews(WmNewsDto wmNewsDto,Integer status) {
        //判断参数是否为空
        if(wmNewsDto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //添加新闻信息
        WmNews wmNews = getwmNews(wmNewsDto);
        //获取用户id
        Integer apUserId = WmThreadLocalUtils.getUser().getApUserId();
        wmNews.setSubmitedTime(new Date());
        wmNews.setUserId(apUserId);
        //获取图片
        String images = wmNewsDto.getImages().toString();
        //替换url
        String replace = images.replace("[", "").replace("]", "").replace(" ", "");
        wmNews.setImages(replace);

        if(wmNewsDto.getId()==null){
            //添加文章
            wmNewsMapper.insert(wmNews);
        }else{
            LambdaQueryWrapper<WmNewsMaterial> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(WmNewsMaterial::getNewsId,wmNews.getId());
            newsMaterialMapper.delete(queryWrapper);

            wmNewsMapper.updateById(wmNews);
        }
        //添加内容图片和关联表的数据
        addNewsMatieial(wmNewsDto,wmNews);
        //修改封面图片的信息和进行封面图片与新闻的关联
        updateNewsMedia(wmNewsDto,wmNews);



        kafkaTemplate.send(NewsAutoScanConstants.Wm_NEWS_AUTO_SCAN_TOPIC, JSON.toJSONString(wmNews.getId()));
        return ResponseResult.errorResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public WmNews findById(Integer id) {

        //判断参数是否为空
        if(id==null){
            return null;
        }

       return wmNewsMapper.selectById(id);
    }

    @Override
    public ResponseResult findNews(NewsAuthDto dto) {
        //判断参数是否为空
        if(dto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //计算page总页数
        int Page=(dto.getPage()-1)*dto.getSize();
        //进行查询
        List<WmNewsVo> wmNewsVos=wmNewsMapper.findList(dto.getTitle(),Page,dto.getSize());
        Integer integer = wmNewsMapper.selectCount(null);

        //封装数据返回
        ResponseResult responseResult = new PageResponseResult(dto.getPage(),dto.getSize(),integer);
        responseResult.setData(wmNewsVos);
        return responseResult;
    }

    @Override
    public ResponseResult updateNews(WmNews wmNews) {
        wmNewsMapper.updateById(wmNews);
        return null;
    }

    @Override
    public List<WmNews> findAll() {
        return wmNewsMapper.selectList(null);
    }

    @Override
    public ResponseResult one(Integer id) {
        WmNews wmNews = wmNewsMapper.selectById(id);
        return ResponseResult.okResult(wmNews);
    }

    @Override
    public ResponseResult auth_pass(WmNewsAuthDto wmNewsAuthDto) {

        //判断参数是否为空
        if(wmNewsAuthDto!=null){

        }

        //修改参数
        WmNews wmNews = new WmNews();
        wmNews.setId(wmNewsAuthDto.getId());
        if(wmNewsAuthDto!=null){
            wmNews.setReason(wmNewsAuthDto.getMsg());
        }
        if(wmNewsAuthDto.getStatus()==4){
            wmNews.setStatus(8);
        }else{
            wmNews.setStatus(wmNewsAuthDto.getStatus());
        }
        wmNewsMapper.updateById(wmNews);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult down_or_up(WmNews wmNews) {
        wmNewsMapper.updateById(wmNews);
        WmNews wmNews1 = wmNewsMapper.selectById(wmNews.getId());
        HashMap<String, String> map = new HashMap<>();
        map.put("Articel",wmNews1.getArticleId().toString());
        map.put("enable",wmNews1.getEnable().toString());
        kafkaTemplate.send(NewsAutoScanConstants.Wm_News_enable, JSON.toJSONString(map));
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    public WmNews getwmNews(WmNewsDto wmNewsDto){
        //进行新闻内容的添加
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(wmNewsDto,wmNews);
        return wmNews;
    }

    public void updateNewsMedia(WmNewsDto wmNewsDto,WmNews wmNews){
        //获取封面图片
        List<String> rul = wmNewsDto.getImages();
        if(wmNews.getType()==WedisContans.MEDIA_TYPE_AUTO){
            int size = rul.size();
            if(size==WedisContans.MEDIA_TYPE){
                wmNews.setType(WedisContans.MEDIA_TYPE);
            }else if(WedisContans.MEDIA_TYPE1==size){
                wmNews.setType(WedisContans.MEDIA_TYPE1);
                rul = rul.stream().limit(1).collect(Collectors.toList());
            }else if(WedisContans.MEDIA_TYPE3==size){
                wmNews.setType(WedisContans.MEDIA_TYPE3);
                rul = rul.stream().limit(3).collect(Collectors.toList());
            }
        }
        //修改新闻的封面图片信息
        LambdaQueryWrapper<WmNews> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WmNews::getId,wmNews.getId());
        queryWrapper.eq(WmNews::getType,wmNews.getType());
        queryWrapper.eq(WmNews::getImages,rul.toString());
        wmNewsMapper.update(wmNews,queryWrapper);
        //获取封面图片的id
        List<Integer> ids = getids(rul, wmNews);
        newsMaterialMapper.newsMaterialAdd(ids,wmNews.getId(),WedisContans.MEDIA_TYPE1);
    }

    public List<Integer> getids(List<String> imgUrl,WmNews wmNews){
        //进行查询获取图片id
        LambdaQueryWrapper<WmMaterial> maquery = new LambdaQueryWrapper<>();
        maquery.eq(WmMaterial::getUserId,wmNews.getUserId());
        maquery.in(WmMaterial::getUrl,imgUrl);

        List<WmMaterial> wmMaterials = mertilMapper.selectList(maquery);

        //转换成 map
        Map<String, Integer> co = wmMaterials.stream().collect(Collectors.toMap(WmMaterial::getUrl, WmMaterial::getId));

        ArrayList<Integer> ids = new ArrayList<>();
        //遍历url取出id
        for (String s : imgUrl) {
            Integer integer = co.get(s);

            //进行判断是否有这个图片
            if(integer==null){
                return null;
            }

            ids.add(integer);
        }
        return ids;
    }

    public ResponseResult addNewsMatieial(WmNewsDto wmNewsDto,WmNews wmNews){
        //获取内容图片
        String content = wmNewsDto.getContent();

        List<Map> maps = JSON.parseArray(content, Map.class);

        //遍历map获取url
        List<String> url = new ArrayList<>();
        for (Map map : maps) {
            if(map.get("type").equals("image")){
                url.add(map.get("value").toString());
            }
        }

        //进行查询获取图片id
        LambdaQueryWrapper<WmMaterial> maquery = new LambdaQueryWrapper<>();
        maquery.eq(WmMaterial::getUserId,wmNews.getUserId());
        maquery.in(WmMaterial::getUrl,url);

        List<WmMaterial> wmMaterials = mertilMapper.selectList(maquery);

        //转换成 map
        Map<String, Integer> co = wmMaterials.stream().collect(Collectors.toMap(WmMaterial::getUrl, WmMaterial::getId));

        ArrayList<Integer> ids = new ArrayList<>();
        //遍历url取出id
        for (String s : url) {
            Integer integer = co.get(s);

            //进行判断是否有这个图片
            if(integer==null){
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"沒有关联图片");
            }

            ids.add(integer);
        }
        //添加内容图片和关联新闻的中间表
        newsMaterialMapper.newsMaterialAdd(ids,wmNews.getId(), WedisContans.MEDIA_TYPE);
        return null;
    }

}